<template>
  <div class="page-new-live-room">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{
          !dataForm.roomId ? $t('live.addNewLiveRoom') : $t('live.viewLRoomInfo')
        }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item
        :label="$t('live.liveName')"
        prop="name"
      >
        <el-input
          v-model.trim="dataForm.name"
          :disabled="dataForm.liveStatus !== 0"
          maxlength="17"
          show-word-limit
          style="width:534px"
        />
      </el-form-item>
      <el-form-item
        :label="$t('live.anchorName')"
        prop="nickName"
      >
        <el-input
          v-model.trim="dataForm.nickName"
          maxlength="15"
          :disabled="dataForm.liveStatus !== 0 && dataForm.liveStatus !== 3"
          show-word-limit
          style="width:534px"
        />
        <p class="live-tips">
          {{ $t("live.liveTip1") }}
        </p>
      </el-form-item>
      <el-form-item
        :label="$t('live.anchorMobile')"
        prop="userMobile"
      >
        <el-input
          v-model="dataForm.userMobile"
          :maxlength="11"
          :disabled="dataForm.liveStatus !== 0 && dataForm.liveStatus !== 3"
          style="width:534px"
        />
      </el-form-item>
      <el-form-item
        :label="$t('live.liveTime')"
        class="liveTime"
      >
        <div class="live-time-row">
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="dataForm.startTime"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              type="date"
              :placeholder="$t('live.chooseStartDate')"
              :picker-options="pickerOptions"
              value-format="YYYY-MM-DD"
              style="width:144px"
              @change="onChangeTime"
            />
            <el-time-select
              v-model="startTimeValue"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:106px"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              :placeholder="$t('time.startTime')"
              @change="onChangeTime"
            />
          </el-form-item>
          <div class="tip">
            {{ $t("time.tip") }}
          </div>
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              type="date"
              :placeholder="$t('live.chooseEndDate')"
              :picker-options="pickerOptions"
              value-format="YYYY-MM-DD"
              style="width:144px"
              @change="onChangeTime"
            />
            <el-time-select
              v-model="endTimeValue"
              start="00:00"
              step="00:30"
              end="23:30"
              style="width:106px"
              :disabled="dataForm.liveStatus !== 0 || isDisabledDate"
              :placeholder="$t('time.endTime')"
              @change="onChangeTime"
            />
          </el-form-item>
          <br>
        </div>
        <p class="live-tips">
          {{ $t("live.liveTimeTip") }}
        </p>
      </el-form-item>
      <el-form-item
        :label="$t('live.liveBackgroundImage')"
        prop="coverImg"
      >
        <img-upload
          v-model="dataForm.coverImg"
          :disabled="dataForm.liveStatus !== 0"
          @update:model-value="onValidateField('coverImg')"
        />
        <p class="live-tips">
          {{ $t("live.recommendedSize") }}：1080{{ $t("live.pixel") }} * 1920{{ $t("live.pixel") }}
        </p>
      </el-form-item>
      <!-- <el-form-item
        :label="$t('live.anchorSharingPicture')"
        prop="shareImg"
      >
        <img-upload
          v-model="dataForm.shareImg"
          :disabled="dataForm.liveStatus !== 0"
        />
        <p class="live-tips">
          {{ $t("live.recommendedSize") }}：800{{ $t("live.pixel") }} * 640{{ $t("live.pixel") }}
        </p>
      </el-form-item> -->
      <el-form-item
        :label="$t('live.liveCoverImage')"
        prop="feedsImg"
      >
        <img-upload
          v-model="dataForm.feedsImg"
          :disabled="dataForm.liveStatus !== 0"
          @update:model-value="onValidateField('feedsImg')"
        />
        <p class="live-tips">
          {{ $t("live.recommendedSize") }}：{{ $t("live.recomImaSizeIs") }} 800{{ $t("live.pixel") }} * 800{{
            $t("live.pixel") }}
        </p>
      </el-form-item>
      <el-form-item
        :label="$t('live.prod') + ':'"
        required
      >
        <div class="prod-card">
          <div
            v-for="(liveProd, index) in liveRoomProdList"
            :key="index"
          >
            <el-card
              :body-style="{ padding: '0px' }"
              style="height: 160px; width: 120px; margin-bottom: 15px;margin-right: 10px;"
            >
              <prod-pic
                height="104px"
                width="100%"
                :pic="liveProd.pic"
              />
              <div class="card-prod-bottom">
                <span class="card-prod-name">{{ liveProd.prodName }}</span>
                <el-button
                  type="text"
                  :disabled="dataForm.liveStatus !== 0"
                  class="card-prod-name-button"
                  @click="deleteSelectProd(index)"
                >
                  {{ $t("text.delBtn") }}
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
        <div
          v-if="dataForm.liveStatus === 0"
          :class="[dataForm.liveStatus !== 0 ? 'disabled-btn' : '', 'default-btn']"
          @click="addProd()"
        >
          {{ $t("product.select") }}
        </div>
        <div v-if="dataForm.liveStatus !== 0 && liveRoomProdList.length===0">
          无
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="back()"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          v-if="dataForm.liveStatus === 0 || dataForm.liveStatus === 3"
          class="default-btn primary-btn"
          @click="dataFormSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </el-form-item>
    </el-form>
    <!-- 商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      @refresh-select-prods="selectIndexProd"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const Data = reactive({
  pickerOptions: {
    disabledDate (time) {
      return time.getTime() < (new Date(new Date(new Date().toLocaleDateString()).getTime()).getTime())
    }
  },
  prodsSelectVisible: false,
  isSubmit: false,
  liveRoomProdList: [],
  dataForm: {
    roomId: null,
    name: null,
    nickName: null,
    userMobile: null,
    coverImg: null,
    shareImg: null,
    feedsImg: null,
    liveStatus: null,
    startTime: null,
    endTime: null,
    prodIds: []
  },
  startTimeValue: '',
  endTimeValue: '',
  isDisabledDate: false
})
const { pickerOptions, prodsSelectVisible, liveRoomProdList, dataForm, startTimeValue, endTimeValue, isDisabledDate } = toRefs(Data)

const onChangeTime = () => {
  onValidateField('startTime')
  onValidateField('endTime')
}

const onValidateField = (field) => {
  dataFormRef.value?.validateField(field)
}

const validateMobile = (rule, value, callback) => {
  if (Data.dataForm.userMobile) {
    const mobile = /^(?:(?:\+|00)86)?1\d{2}([\d*]{4})\d{4}$/
    if (mobile.test(value)) {
      callback()
    } else {
      callback(new Error($t('shopProcess.telErrorTips')))
    }
  } else if (!isMobile(value)) {
    callback(new Error($t('sys.mobilePhoneError')))
  } else {
    callback()
  }
}

const validatorDateRange = (rule, value, callback) => {
  if (rule.field === 'startTime' && (!Data.startTimeValue || !Data.dataForm.startTime)) {
    callback(new Error($t('publics.noNull')))
  }
  if (rule.field === 'endTime' && (!Data.endTimeValue || !Data.dataForm.endTime)) {
    callback(new Error($t('publics.noNull')))
  }
  if (Data.dataForm.liveStatus === 3 || Data.isDisabledDate) {
    callback()
  }
  const startTime = Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00'
  const endTime = Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00'
  if (rule.field === 'startTime' && new Date() > Date.parse(startTime)) {
    callback(new Error($t('groups.startTime')))
  }
  if (rule.field === 'startTime' && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('marketing.timeCanThanOrEqualTo')))
  }
  if (rule.field === 'endTime' && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  }
  callback()
}

const dataRule = reactive({
  name: [
    { required: true, message: $t('live.liveRoomNameCannotBeEmpty'), trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: $t('live.anchoBeEmp'), trigger: 'blur' }
  ],
  userMobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateMobile, trigger: 'blur' }
  ],
  coverImg: [
    { required: true, message: $t('live.backEmpty'), trigger: 'blur' }
  ],
  shareImg: [
    { required: true, message: $t('live.hostSnPict'), trigger: 'blur' }
  ],
  feedsImg: [
    { required: true, message: $t('live.liveEmpty'), trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('user.startDate') + $t('publics.noNull'), trigger: 'blur' },
    { required: true, validator: validatorDateRange, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('user.endDate') + $t('publics.noNull'), trigger: 'blur' },
    { required: true, validator: validatorDateRange, trigger: 'blur' }
  ]
})

const commonStore = useCommonStore()
onMounted(() => {
  const flag = sessionStorage.getItem('bbcLiveRoomData') !== 'undefined'
  const data = flag ? JSON.parse(sessionStorage.getItem('bbcLiveRoomData')) : null
  init(data)
  const title = !Data.dataForm.roomId ? $t('live.addNewLiveRoom') : $t('live.viewLRoomInfo')
  commonStore.replaceSelectMenu(title)
})

const dataFormRef = ref()
const init = (data) => {
  if (data) {
    Data.dataForm = data
    Data.dataForm.roomId = data.roomId
  } else {
    Data.dataForm.liveStatus = 0
  }
  Data.isSubmit = false
  Data.liveRoomProdList = []
  nextTick(() => {
    dataFormRef.value.resetFields()
    const datetimeRange = getDateTimeRange()
    Data.dataForm.startTime = datetimeRange.startTime
    Data.dataForm.endTime = datetimeRange.endTime
    Data.startTimeValue = datetimeRange.currentTime
    Data.endTimeValue = datetimeRange.currentTime
    if (Data.dataForm.roomId) {
      http({
        url: http.adornUrl('/multishop/live/liveRoom/info/' + Data.dataForm.roomId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        Data.dataForm = JSON.parse(JSON.stringify(data))
        Data.tmepStartTime = data.startTime
        Data.startTimeValue = Data.dataForm.startTime ? Data.dataForm.startTime.substring(11, Data.dataForm.startTime.length - 3) : ''
        Data.endTimeValue = Data.dataForm.endTime ? Data.dataForm.endTime.substring(11, Data.dataForm.endTime.length - 3) : ''
        Data.dataForm.startTime = getParseTime(Data.dataForm.startTime, '{y}-{m}-{d}')
        Data.dataForm.endTime = getParseTime(Data.dataForm.endTime, '{y}-{m}-{d}')
        // 当前时间超出开始时间时，开始时间不可修改
        if (new Date() > Date.parse(data.startTime)) {
          Data.isDisabledDate = true
        } else {
          startTimeCountDown()
        }
      })
      // 获取商品列表
      http({
        url: http.adornUrl('/multishop/live/liveRoom/listLiveRoomProd'),
        method: 'get',
        params: http.adornParams({
          roomId: Data.dataForm.roomId
        })
      }).then(({ data }) => {
        Data.liveRoomProdList = data.map(x => x.product)
        if (Data.dataForm.status !== null && Data.dataForm.status === -1) {
          // 用户注销
          ElMessage($t('live.liveAnchorNotExist'))
        } else if (Data.dataForm.status !== null && Data.dataForm.status !== 1) {
          // 用户禁用
          ElMessageBox.confirm($t('live.liveAnchorError'))
        }
      })
    }
  })
}

// 直播开始时间倒计时
const startTimeCountDown = () => {
  if (new Date().getTime() < Date.parse(Data.tmepStartTime)) {
    Data.liveTimer = setTimeout(Data.startTimeCountDown, 1000)
  } else {
    Data.isDisabledDate = true
    Data.liveTimer && clearTimeout(Data.liveTimer)
  }
}

// 表单提交
const dataFormSubmit = () => {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      if (Data.isSubmit) {
        return
      }
      Data.dataForm.prodIds = Data.liveRoomProdList.map(x => x.prodId)
      const startTime = Data.dataForm.startTime
      const endTime = Data.dataForm.endTime
      Data.dataForm.startTime = Data.dataForm.startTime && Data.startTimeValue ? Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00' : ''
      Data.dataForm.endTime = Data.dataForm.endTime && Data.endTimeValue ? Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00' : ''
      Data.isSubmit = true
      http({
        url: http.adornUrl('/multishop/live/liveRoom'),
        method: Data.dataForm.roomId ? 'put' : 'post',
        data: http.adornData(Data.dataForm)
      }).then(() => {
        Data.isSubmit = true
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            back()
          }
        })
      }).catch(() => {
        Data.isSubmit = false
      })
      Data.dataForm.startTime = startTime
      Data.dataForm.endTime = endTime
    }
  })
}

// 添加指定商品
const selectIndexProd = (prods) => {
  Data.prodsSelectVisible = false
  if (prods) {
    Data.liveRoomProdList = prods
  }
}

const deleteSelectProd = (index) => {
  Data.liveRoomProdList.splice(index, 1)
}

const prodsSelectRef = ref()
// 打开选择商品
const addProd = () => {
  Data.prodsSelectVisible = true
  nextTick(() => {
    prodsSelectRef.value.init(Data.liveRoomProdList)
  })
}

const router = useRouter()
const back = () => {
  router.push({
    path: '/marketing/live-room/index'
  })
}
</script>

<style lang="scss" scoped>
.page-new-live-room {
  :deep(.el-form-item__content) {
    display: block;
  }

  .live-tips {
    color: #aaa;
    line-height: 20px;
    margin: 0;
    padding: 0;
  }

  .live-time-row {
    display: flex;

    .tip {
      margin: 0 10px;
    }
  }

  .liveTime ::v-deep(.el-form-item__error) {
    top: 60px;
  }

  .liveTime ::v-deep(.el-form-item__label:before) {
    content: '*';
    color: #F56C6C;
    margin-right: 4px;
  }

  .prod-card {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
